package com.eunion.web.cms.entity.spec;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import com.eunion.web.cms.entity.Major;

public final class MajorSpec {

    public static Specification<Major> build(Major queryBean) {
        return new MajorQuery(queryBean);
    }

    public static Specification<Major> build(Major queryBean,boolean accurate) {
        return new MajorQuery(queryBean,accurate);
    }

    private static class MajorQuery implements Specification<Major> {

        private Major queryBean;
        private boolean accurate;

        private MajorQuery(Major queryBean) {
            this.queryBean = queryBean;
        }

        private MajorQuery(Major queryBean,boolean accurate) {
            this.queryBean = queryBean;
            this.accurate = accurate;
        }

        @Override
        public Predicate toPredicate(Root<Major> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> list = getPredicates(root, query, cb, queryBean,accurate);
            Predicate[] preList = new Predicate[list.size()];
            return cb.and(list.toArray(preList));
        }

    }

    private static List<Predicate> getPredicates(Root<Major> root, CriteriaQuery<?> query, CriteriaBuilder cb,
            Major queryBean,boolean accurate) {
        // 条件集合
        List<Predicate> list = new ArrayList<>();

        // 专业类型代码条件
        String majorCode = queryBean.getMajorCode();
        if(accurate) {
            if (StringUtils.isNotBlank(majorCode)) {
                list.add(cb.equal(root.get("majorCode"),majorCode.trim()));
            }
            return list;
        }
        if (StringUtils.isNotBlank(majorCode)) {
            list.add(cb.like(root.get("majorCode"), "%" + majorCode.trim() + "%"));
        }

        // 专业类型名称条件
        String majorName = queryBean.getMajorName();
        if (StringUtils.isNotBlank(majorName)) {
            list.add(cb.like(root.get("majorName"), "%" + majorName.trim() + "%"));
        }

        // 专业层次条件
        Integer majorLevel = queryBean.getMajorLevel();
        if (majorLevel != null && majorLevel > 0) {
            list.add(cb.equal(root.get("majorLevel"), majorLevel));
        }

        // 专业一级分类条件
        String majorSubject = queryBean.getMajorSubject();
        if (StringUtils.isNotBlank(majorSubject)) {
            list.add(cb.equal(root.get("majorSubject"), majorSubject.trim()));
        }

        // 专业二级分类条件
        String majorClass = queryBean.getMajorClass();
        if (StringUtils.isNotBlank(majorClass)) {
            list.add(cb.equal(root.get("majorClass"), majorClass.trim()));
        }

        return list;
    }
}
